// Background Service Worker for Boss Auto Delivery Extension

// 插件安装时的初始化
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('Boss直聘自动投递插件已安装');
    
    // 设置默认配置
    chrome.storage.local.set({
      boss_auto_delivery_settings: {
        dailyLimit: 50,
        deliveryInterval: 3,
        autoScroll: true,
        blacklistCompanies: [],
        filterKeywords: [],
        deliveryMessage: '您好，我对这个职位很感兴趣，希望能有机会详细了解。'
      },
      boss_auto_delivery_state: {
        isRunning: false,
        isPaused: false,
        todayDeliveryCount: 0,
        totalDeliveryCount: 0,
        currentPage: 1
      }
    });
  }
});

// 监听来自content script和popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.action) {
    case 'GET_DELIVERY_STATUS':
      handleGetDeliveryStatus(sendResponse);
      break;
    case 'UPDATE_DELIVERY_COUNT':
      handleUpdateDeliveryCount(message.data, sendResponse);
      break;
    case 'DELIVERY_COMPLETED':
      handleDeliveryCompleted(message.data, sendResponse);
      break;
    case 'DELIVERY_ERROR':
      handleDeliveryError(message.data, sendResponse);
      break;
    default:
      sendResponse({ success: false, error: 'Unknown action' });
  }
  
  return true; // 保持消息通道开放
});

// 获取投递状态
async function handleGetDeliveryStatus(sendResponse: (response: any) => void) {
  try {
    const result = await chrome.storage.local.get(['boss_auto_delivery_state']);
    sendResponse({ 
      success: true, 
      data: result.boss_auto_delivery_state 
    });
  } catch (error) {
    sendResponse({ 
      success: false, 
      error: error instanceof Error ? error.message : 'Unknown error' 
    });
  }
}

// 更新投递数量
async function handleUpdateDeliveryCount(data: any, sendResponse: (response: any) => void) {
  try {
    const result = await chrome.storage.local.get(['boss_auto_delivery_state']);
    const currentState = result.boss_auto_delivery_state || {};
    
    const updatedState = {
      ...currentState,
      todayDeliveryCount: data.todayCount || currentState.todayDeliveryCount,
      totalDeliveryCount: data.totalCount || currentState.totalDeliveryCount
    };
    
    await chrome.storage.local.set({ boss_auto_delivery_state: updatedState });
    
    sendResponse({ success: true, data: updatedState });
  } catch (error) {
    sendResponse({ 
      success: false, 
      error: error instanceof Error ? error.message : 'Unknown error' 
    });
  }
}

// 投递完成处理
async function handleDeliveryCompleted(data: any, sendResponse: (response: any) => void) {
  try {
    // 更新状态为完成
    const result = await chrome.storage.local.get(['boss_auto_delivery_state']);
    const currentState = result.boss_auto_delivery_state || {};
    
    const updatedState = {
      ...currentState,
      isRunning: false,
      isPaused: false
    };
    
    await chrome.storage.local.set({ boss_auto_delivery_state: updatedState });
    
    // 发送通知
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: 'Boss直聘自动投递',
      message: `投递完成！共投递 ${data.count || 0} 个职位`
    });
    
    sendResponse({ success: true });
  } catch (error) {
    sendResponse({ 
      success: false, 
      error: error instanceof Error ? error.message : 'Unknown error' 
    });
  }
}

// 投递错误处理
async function handleDeliveryError(data: any, sendResponse: (response: any) => void) {
  try {
    // 更新状态
    const result = await chrome.storage.local.get(['boss_auto_delivery_state']);
    const currentState = result.boss_auto_delivery_state || {};
    
    const updatedState = {
      ...currentState,
      isRunning: false,
      isPaused: false
    };
    
    await chrome.storage.local.set({ boss_auto_delivery_state: updatedState });
    
    // 发送错误通知
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: 'Boss直聘自动投递',
      message: `投递过程中出现错误: ${data.error || '未知错误'}`
    });
    
    sendResponse({ success: true });
  } catch (error) {
    sendResponse({ 
      success: false, 
      error: error instanceof Error ? error.message : 'Unknown error' 
    });
  }
}

// 定期清理过期数据
chrome.alarms.create('cleanupData', { periodInMinutes: 60 * 24 }); // 每天清理一次

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'cleanupData') {
    cleanupExpiredData();
  }
});

// 清理过期数据
async function cleanupExpiredData() {
  try {
    const result = await chrome.storage.local.get(['boss_auto_delivery_daily_count']);
    const dailyData = result.boss_auto_delivery_daily_count || {};
    
    // 清理7天前的数据
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    
    Object.keys(dailyData).forEach(date => {
      if (new Date(date) < sevenDaysAgo) {
        delete dailyData[date];
      }
    });
    
    await chrome.storage.local.set({ boss_auto_delivery_daily_count: dailyData });
    console.log('过期数据清理完成');
  } catch (error) {
    console.error('清理过期数据失败:', error);
  }
}

// 监听标签页更新，检测Boss直聘页面
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url?.includes('zhipin.com')) {
    // 可以在这里添加页面加载完成后的逻辑
    console.log('Boss直聘页面加载完成');
  }
});

// 处理插件图标点击
chrome.action.onClicked.addListener((tab) => {
  // 如果没有popup，这里可以处理点击事件
  // 当前配置了popup，所以这个事件不会触发
});

export {};